package com.ny.impl;

import com.ny.entity.Student;
import com.ny.service.StudentServiceImpl;
import com.ny.until.SqlConnection;
import dao.StudentDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentDaoImpl implements StudentDao {
    Connection connection = SqlConnection.getCon();

    public StudentDaoImpl() throws SQLException, ClassNotFoundException {

    }

    public int add(Student student) throws SQLException {
        String sql = "insert into students(name,password,phone) values(?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, student.getStudentName());
        preparedStatement.setString(2, student.getStudentPassword());
        preparedStatement.setString(3, student.getStudentPhone());
        return preparedStatement.executeUpdate();
    }

    public Student login(String studentName, String studentPassword) throws SQLException {
        String sql = "select * from students where name = ? and password = ?";
        PreparedStatement preparedStatement = this.connection.prepareStatement(sql);
        preparedStatement.setString(1, studentName);
        preparedStatement.setString(2, studentPassword);
         ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            Student student = new Student();
            student.setStudentId(resultSet.getInt("student_id"));
            student.setStudentName(resultSet.getString("name"));
            student.setStudentPhone(resultSet.getString("phone"));
            student.setStudentPassword(resultSet.getString("password"));
            return student;
        } else {
            return null;
        }
    }
}
